const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cors = require('koa-cors');
const multer = require('@koa/multer');
const path = require('path');
const fs = require('fs');

const app = new Koa();
const router = new Router();

// 确保 uploads 目录存在
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
    fs.mkdirSync(uploadsDir, { recursive: true });
}

// 中间件
app.use(cors());
app.use(bodyParser());

// 静态文件 - uploads
app.use(async (ctx, next) => {
    if (ctx.path.startsWith('/uploads/')) {
        const filePath = path.join(uploadsDir, ctx.path.replace('/uploads/', ''));
        if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
            ctx.type = path.extname(filePath);
            ctx.body = fs.createReadStream(filePath);
            return;
        }
    }
    await next();
});

// 静态文件 - static
const staticDir = path.join(__dirname, '..', 'static');
app.use(async (ctx, next) => {
    if (ctx.path.startsWith('/static/')) {
        const filePath = path.join(staticDir, ctx.path.replace('/static/', ''));
        if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
            ctx.type = path.extname(filePath);
            ctx.body = fs.createReadStream(filePath);
            return;
        }
    }
    await next();
});

// 文件上传配置
const upload = multer({
    dest: uploadsDir,
    limits: { fileSize: 50 * 1024 * 1024 }
});

// 上传路由
router.post('/api/upload/audio', upload.single('audio'), async (ctx) => {
    try {
        if (!ctx.request.file) {
            ctx.status = 400;
            ctx.body = { code: -1, message: '没有收到文件' };
            return;
        }

        const file = ctx.request.file;
        const ext = path.extname(file.originalname);
        const newFilename = file.filename + ext;
        const oldPath = file.path;
        const newPath = path.join(uploadsDir, newFilename);

        fs.renameSync(oldPath, newPath);

        ctx.body = {
            code: 0,
            message: '上传成功',
            data: {
                url: `/uploads/${newFilename}`,
                filename: newFilename,
                originalName: file.originalname,
                size: file.size
            }
        };
    } catch (error) {
        console.error('上传失败:', error);
        ctx.status = 500;
        ctx.body = { code: -1, message: '上传失败: ' + error.message };
    }
});

// 根路由
router.get('/', async (ctx) => {
    ctx.body = { message: '音乐服务器运行中', version: '1.0.0' };
});

// 健康检查
router.get('/health', async (ctx) => {
    ctx.body = { status: 'ok' };
});

app.use(router.routes());
app.use(router.allowedMethods());

const PORT = 3000;
app.listen(PORT, '0.0.0.0', () => {
    console.log('='.repeat(50));
    console.log('🎵 音乐服务器已启动成功！');
    console.log('='.repeat(50));
    console.log(`📡 服务器地址: http://localhost:${PORT}`);
    console.log(`📡 网络地址: http://172.29.99.148:${PORT}`);
    console.log(`📁 上传目录: ${uploadsDir}`);
    console.log(`📁 静态目录: ${staticDir}`);
    console.log(`🚀 上传接口: POST /api/upload/audio`);
    console.log(`🎵 静态文件: /static/brightest_star.mp3`);
    console.log('='.repeat(50));
});
